package twittertracker;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.xml.sax.InputSource;

import com.mysql.jdbc.PreparedStatement;

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterTrackApp {

	/**
	 * @param args
	 */

	private static Connection con = null;
	private static Statement st = null;
	private static ResultSet rs = null;
	
	public static void main(String[] args) {
		
	   // twitterStream.links(0);
		//setTwitterStatus("hello");
		//getStatus();
		//getStreamingTwitterData();
		//searchForTweets("Eagle Greek");
		//getURL();
		//setStatus("helloq");
		streamTest();
		//connectMySQLDB();
	}
	private static void connectMySQLDB1() {
		try {
			Context context = new InitialContext();

			DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
			
			
		} catch (NamingException e) {
			e.printStackTrace();
		}

	}
	private static void connectMySQLDB() {
		// Connect to MySQL database
		Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/world";
        String user = "root";
        String password = "P4ssw0rd";

        try {
        	Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url, user, password);
            System.out.println(con);
            System.out.println( con.isValid(1));
            System.out.println(url);
            st = con.createStatement();
            System.out.println(st.getResultSet());
            
            //rs = st.executeQuery("select id from twitter where id =(select max(id) from twitter) ");
            rs = st.executeQuery("select * from country");
            System.out.println(st.getResultSet());
            System.out.println(rs.getRow());
            System.out.println(rs.wasNull());
            //System.out.println(rs.getString(1));
            while (rs.next()) {
            	System.out.println(rs.getString(1) + " " + rs.getString(2));
            	
			}
            //int n = rs.getInt(0);
//            System.out.println(n);
//            String sql = "INSERT INTO twitter " +"VALUES (100, 'Zara', 'Ali', 18)";
//            //rs = st.executeQuery("SELECT Name FROM twitter limit 10");
//            if (rs.next()) {
//                System.out.println(rs.getString(1));
//            }
           con.close();
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Version.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
 
	}
	private static void streamTest() {
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey("oF6y3WZrRxNi7wBc8a0qw");
		cb.setOAuthConsumerSecret("JEFvW3mEIEOXlumSbQOdMF70cb9tAZZe6ZP8ULetLM");
		cb.setOAuthAccessToken("354960461-BfQUjAsSzV3YwQpKaqnJw0ANU8B8DwbJCWYdKWcc");
		cb.setOAuthAccessTokenSecret("uKH8C8jKPND3H0AjqVoq0E7dKLPKwzhF0Z1jbRKrU4");
		
		// Connect to MySQL database

		
	    StatusListener listener = new StatusListener(){
	        public void onStatus(Status status) {
	        	GeoLocation location = status.getGeoLocation();
	        	if (null != location) {
	        		//California Lookout fire 2012: 34.501 latitude, -119.783 longitude
	        		//hurriance Sandy: longitude: -75.0,latitude: 40.0
	        		double latitude = Math.abs(location.getLatitude() - 40.0);
	        		double longitude = Math.abs(location.getLongitude() + 122.0 );
	        		if(latitude <2.0 && longitude < 2.0){
	        			Connection con = null;
	        			//PreparedStatement st = null;
	        	        Statement st = null;
	        	        ResultSet rs = null;

	        	        String url = "jdbc:mysql://localhost:3306/test";
	        	        String user = "root";
	        	        String password = "P4ssw0rd";

	        	        try {
	        	            con = DriverManager.getConnection(url, user, password);
	        	            st = con.createStatement();
	        	            //rs = st.executeQuery("select idtwitter from twitter where idtwitter =(select max(idtwitter) from twitter) ");
	        	            rs = st.executeQuery("select idsandy from sandy where idsandy =(select max(idsandy) from sandy) ");
	        	            	int n =0;
	        	            	if (rs.next()) {
	        	            		n = rs.getInt(1) +1;
								}
	        	            	else
	        	            	{
	        	            		n = 0;
	        	            	}
		        	            System.out.println(n);
		        	            String tweet = status.getText();
		        	            Date time = status.getCreatedAt();
		        	            String twitterTime = Integer.toString(time.getYear())+"-"+Integer.toString(time.getMonth()) + "-" +Integer.toString(time.getDay());
		        	            		
		        	            tweet = tweet.replace("'", "''");
//		        	            s = Replace(s, "&", "&amp;");  
//		        	            s = Replace(s, "<", "&lt;");  
//		        	            s = Replace(s, ">", "&gt;");  
//		        	            s = Replace(s, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");  
//		        	            s = Replace(s, "\r\n", "\n");  
//		        	            s = Replace(s, "\n", "<br>");  
//		        	            s = Replace(s, "  ", "&nbsp;&nbsp;");  
//		        	            s = Replace(s, "'", "&#39;");  
//		        	            s = Replace(s, "\\", "&#92;"); 
			    	            //String sql = "INSERT INTO twitter (idtwitter,username,tweet,latitude,longitude)" +"VALUES (" + Integer.toString(n)+ ",'" + status.getUser().getName() + "','"+ tweet+"',"+ Double.toString(location.getLatitude())+"," + Double.toString(location.getLongitude());
			    	            
//		        	            String sql = "INSERT INTO twitter (idtwitter,time,username,tweet,latitude,longitude)"
//			    	            +"VALUES (" + Integer.toString(n)+",'" +time.toString()+ "','" + status.getUser().getName() + "','"
//			    	            + tweet+"',"+ Double.toString(location.getLatitude())+"," + Double.toString(location.getLongitude()) +")";
		        	            String sql = "INSERT INTO sandy (idsandy,time,username,tweet,latitude,longitude)"
			    	            +"VALUES (" + Integer.toString(n)+",'" +time.toString()+ "','" + status.getUser().getScreenName() + "','"
			    	            + tweet+"',"+ Double.toString(location.getLatitude())+"," + Double.toString(location.getLongitude()) +")";

			    	            st.executeUpdate(sql);
			    	            
	        	            rs.close();
	        	            st.close();
	        	            con.close();
	        	        } catch (SQLException ex) {
	        	            Logger lgr = Logger.getLogger(Version.class.getName());
	        	            lgr.log(Level.SEVERE, ex.getMessage(), ex);

	        	        } finally {
	        	            try {
	        	                if (rs != null) {
	        	                    rs.close();
	        	                }
	        	                if (st != null) {
	        	                    st.close();
	        	                }
	        	                if (con != null) {
	        	                    con.close();
	        	                }

	        	            } catch (SQLException ex) {
	        	                Logger lgr = Logger.getLogger(Version.class.getName());
	        	                lgr.log(Level.WARNING, ex.getMessage(), ex);
	        	            }
	        	        }

		        		System.out.println(status.getCreatedAt().toLocaleString()+ " " + status.getUser().getScreenName() + " : " + status.getText() + " location: " + location.getLatitude() +", " + location.getLongitude());
	        		}
				}
	            
	        }
	        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
	        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
	        public void onException(Exception ex) {
	            ex.printStackTrace();
	        }
			@Override
			public void onScrubGeo(long arg0, long arg1) {
				
			}
	    };
	    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
	    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
	    twitterStream.addListener(listener);
	    // user id = 354960461
	    long [] ids = {354960461};
	    FilterQuery filterQuery = new FilterQuery();
	    //double [][] locations ={{40.00,-111.00},{41.00,-111.00},{41.00,-110.00},{40.00,-110.00}};
	    
	  //California Lookout fire 2012: 34.501 latitude, -119.783 longitude
	    //double [][] locations ={{-121.00,33},{-119.00,35}};
	    
	    //hurricane Sandy: 
	    //double [][] locations ={{-76.00,39},{-74.00,41}};
	    //Ponderosa fire
	    double [][] locations ={{-124.00,38},{-120.00,42}};
	    filterQuery.locations(locations);
	    twitterStream.filter(filterQuery);
	    //twitterStream.sample();
	}
	private static void getURL() {
		//URL url = new URL("http://api.map.baidu.com/geocoder" + "?address=" + strAddress + "&output=xml&key=80c1166e6263bd4a1201eff8f2f79466");
		URL url = null;
		try {
			url = new URL("https://api.twitter.com/1/geo/reverse_geocode.json?lat=37.76893497&long=-122.42284884");
			System.out.println(url.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		// prepare an HTTP connection to the geocoder
		HttpURLConnection conn;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.connect();
		    System.out.println(conn.toString());

	        //InputSource geocoderResultInputSource = new InputSource(conn.getInputStream());
	        
	       // System.out.println(geocoderResultInputSource.toString());
	        JSONTokener jsonTokener = new JSONTokener(conn.getInputStream());

	        
	        JSONObject jsonObj = new JSONObject(jsonTokener);
	        String [] names = JSONObject.getNames(jsonObj);
	        JSONObject objResult = jsonObj.getJSONObject(names[1]);
	        String [] namesResult = JSONObject.getNames(objResult);
	        JSONObject objPlaces = objResult.getJSONObject(namesResult[0]);
	        String [] namesPlace = JSONObject.getNames(objPlaces);

	        //JSONArray jArray = new JSONArray(objPlaces.valueToString(objPlaces));
	       // System.out.println("Array Length: " + jArray.length());
	        System.out.println("**************************************");
	        System.out.println(JSONObject.valueToString(jsonObj));
	        System.out.println("**************************************");
	        
	        for (String string : namesPlace) {
	        	System.out.println(string);
			}
	        System.out.println("Names: ");
	        System.out.println("Name[0]= " + names[0]);
	        System.out.println("Name[1]= " + names[1]);
	        for (String string : names) {
	        	System.out.println(string);
			}
	        JSONObject objQuery = jsonObj.getJSONObject(names[1]);
	        System.out.println(names[1] + " : " + JSONObject.valueToString(objQuery));
	        System.out.println("**************************************");
	        JSONObject objCoord = objQuery.getJSONObject("params").getJSONObject("coordinates");
	        System.out.print(objCoord.get("coordinates"));
	        JSONArray array = new JSONArray(objCoord.get("coordinates").toString());
	        System.out.println("**************************************");
	        for (int i = 0; i < array.length(); i++) {
				System.out.println(array.get(i));
			}
	        System.out.println(JSONObject.valueToString(objCoord));
		} catch (IOException e1) {
			e1.printStackTrace();
		}catch (JSONException e2) {
			e2.printStackTrace();
		}
		
	    //System.out.println(url.toString());

		
	}
	private void searchForTweets(String strSearch){
		
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey("oF6y3WZrRxNi7wBc8a0qw");
		cb.setOAuthConsumerSecret("JEFvW3mEIEOXlumSbQOdMF70cb9tAZZe6ZP8ULetLM");
		cb.setOAuthAccessToken("354960461-0q3smvorlVdzwnI86aMWf9YsKUuJ0EvxMlPjQdXQ");
		cb.setOAuthAccessTokenSecret("ORHoyAhZ40jTSeIzbTxzofrszD7jhRK7MExyuXA5kdQ");
		
		TwitterFactory tf = new TwitterFactory(cb.build());
	    Twitter twitter = new TwitterFactory().getInstance();
	    Query query = new Query(strSearch);
	    QueryResult result;
		try {
			result = twitter.search(query);
			List<Tweet> tweetList = result.getTweets();
			
			System.out.println("page: " + result.getPage());
			System.out.println("size: " +result.getTweets().size());

		    for (Tweet tweet : result.getTweets()) {
		    	GeoLocation location = tweet.getGeoLocation();
		    	if (null != location) {
			        System.out.println(tweet.getFromUser() + ":" + tweet.getText() + " location: " + location.getLatitude() + location.getLongitude());
				}
		    }
		} catch (TwitterException e) {
			e.printStackTrace();
		}

	}
	private void setTwitterStatus(String strStatus) {
		System.out.print("hello\n");
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey("oF6y3WZrRxNi7wBc8a0qw");
		cb.setOAuthConsumerSecret("JEFvW3mEIEOXlumSbQOdMF70cb9tAZZe6ZP8ULetLM");
		cb.setOAuthAccessToken("354960461-0q3smvorlVdzwnI86aMWf9YsKUuJ0EvxMlPjQdXQ");
		cb.setOAuthAccessTokenSecret("ORHoyAhZ40jTSeIzbTxzofrszD7jhRK7MExyuXA5kdQ");
		//34ccdd6b6a3a8205a4fc16c3840954d7
		TwitterFactory tf = new TwitterFactory(cb.build());
	    Twitter twitter = tf.getInstance();
	    Status status;
		try {
			status = twitter.updateStatus(strStatus);
			//IDs ids = twitter.getFriendsIDs(0);
		    System.out.println("Successfully updated the status to [" + status.toString() + "].");

		} catch (TwitterException e) {
			e.printStackTrace();
		}
	}
	private static void setStatus(String strStatus) {
		System.out.print("hello\n");
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey("oF6y3WZrRxNi7wBc8a0qw");
		cb.setOAuthConsumerSecret("JEFvW3mEIEOXlumSbQOdMF70cb9tAZZe6ZP8ULetLM");
		cb.setOAuthAccessToken("354960461-BfQUjAsSzV3YwQpKaqnJw0ANU8B8DwbJCWYdKWcc");
		cb.setOAuthAccessTokenSecret("uKH8C8jKPND3H0AjqVoq0E7dKLPKwzhF0Z1jbRKrU4");
		TwitterFactory tf = new TwitterFactory(cb.build());
	    Twitter twitter = tf.getInstance();
	     
	    try {
			Status status = twitter.updateStatus(strStatus);
			System.out.println(status.getText());
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    
	    
	}
	private static  void getStatus(){
		System.out.print("hello\n");
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey("oF6y3WZrRxNi7wBc8a0qw");
		cb.setOAuthConsumerSecret("JEFvW3mEIEOXlumSbQOdMF70cb9tAZZe6ZP8ULetLM");
		cb.setOAuthAccessToken("354960461-BfQUjAsSzV3YwQpKaqnJw0ANU8B8DwbJCWYdKWcc");
		cb.setOAuthAccessTokenSecret("uKH8C8jKPND3H0AjqVoq0E7dKLPKwzhF0Z1jbRKrU4");
		//34ccdd6b6a3a8205a4fc16c3840954d7
		TwitterFactory tf = new TwitterFactory(cb.build());
	    Twitter twitter = tf.getInstance();
	    List<Status> statuses;
		try {
			statuses = twitter.getUserTimeline();
			
		    System.out.println("Showing friends timeline.");
		    for (Status status : statuses) {
		        System.out.println(status.getUser().getName() + ":" +
		                           status.getText() + "  id: " +status.getUser().getId());
		    }
		} catch (TwitterException e) {
			e.printStackTrace();
		}

	}
	public static void getStreamingTwitterData() {
		System.out.print("hello\n");
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey("oF6y3WZrRxNi7wBc8a0qw");
		cb.setOAuthConsumerSecret("JEFvW3mEIEOXlumSbQOdMF70cb9tAZZe6ZP8ULetLM");
		cb.setOAuthAccessToken("354960461-BfQUjAsSzV3YwQpKaqnJw0ANU8B8DwbJCWYdKWcc");
		cb.setOAuthAccessTokenSecret("uKH8C8jKPND3H0AjqVoq0E7dKLPKwzhF0Z1jbRKrU4");
        
        StatusListener listener = new StatusListener() {
            public void onStatus(Status status) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            }

            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };
		TwitterStreamFactory tStrFactory = new TwitterStreamFactory(cb.build());
		//TwitterStream steam = new twitter4j.TwitterS TwitterStreamFactory(listener).getInstance();
        TwitterStream twitterStream = tStrFactory.getInstance();
        twitterStream.addListener(listener);
        twitterStream.links(0);
	}
}
